<?php

	require_once "../../konfigurasi.php";
	require_once "../func_upload_file.php";
	
	koneksi_buka();
	
	if(isset($_GET['id'])){
		$id = $_GET['id'];
	}
	
	if(isset($_POST['id'])){
		$id = $_POST['id'];
	}
	
	if(isset($_POST['nama'])){
		$nama = $_POST['nama'];
	}
	
	if(isset($_POST['tipe_kelas'])){
		$tipe_kelas = $_POST['tipe_kelas'];
	}
	
	if(isset($_POST['pertemuan'])){
		$pertemuan = $_POST["pertemuan"];
	}
	if(isset($_POST['operation'])){
		$operation = $_POST["operation"];
	}
	
	if(isset($_GET['operation'])){
		$operation = $_GET["operation"];
	}
	
	$tgl_daftar = date("Y-m-d");
	$wkt = date("H:i:s");
	
	if($operation=="get_text"){
		$q_siswa = mysql_query("select * from siswa where nis='$nis'");
		if($dt_siswa = mysql_fetch_array($q_siswa)) {
			echo $dt_siswa['nama']." (".$dt_siswa['kelas'].")";
		}
	}else if($operation == "add") {
		
		$path_file = "0";
		if(isset($_FILES["file"]["name"])){
			
			$temp = explode(".", $_FILES["file"]["name"]);
			$extension = end($temp);
			if($extension!=""){
				$path_file = "file_materi/".$nama."_".$tipe_kelas."_".$pertemuan.".".$extension;
			}
			
		}
		
		$q = "INSERT INTO materi
			(nama,file, tipe_kelas,pertemuan_ke) 
			VALUES('$nama','$path_file','$tipe_kelas','$pertemuan')";
		
		$result = mysql_query($q);
		
		if(isset($_FILES["file"]["name"])){
			upload_file("../../".$path_file);
		}
		
		if($result){
			header("Location:../../admin_materi.php");
		}else{
			echo 'failed query :'.$q ;
		}
		
		
	}else if($operation == "edit") {
		
		$path_file = "0";
		if(isset($_FILES["file"]["name"])){
			$temp = explode(".", $_FILES["file"]["name"]);
			$extension = end($temp);
			if($extension!=""){
				$path_file = "file_materi/".$nama."_".$tipe_kelas."_".$pertemuan.".".$extension;
			}
			
		}
		if(!isset($_FILES["file"]["name"]) || $_FILES["file"]["name"]==""){
			$result = mysql_query("UPDATE materi SET 
				nama='$nama',
				tipe_kelas='$tipe_kelas',
				pertemuan_ke='$pertemuan'
				WHERE id=".$id);
			
		}else{
			$q_materi = mysql_query("select * FROM materi WHERE id=".$id);
		
			while($dt = mysql_fetch_array($q_materi)) {
				unlink("../../".$dt['file']);// delete gambar....
			}
			
			$result = mysql_query("UPDATE materi SET 
				nama='$nama',
				tipe_kelas='$tipe_kelas',
				file='$path_file',
				pertemuan_ke='$pertemuan'
				WHERE id=".$id);
				
			if(isset($_FILES["file"]["name"])){
				upload_file("../../".$path_file);
			}
			
		}
		
		
		if($result){
			header("Location:../../admin_materi.php");
		}else{
			echo 'failed';
		}
		
		
	}else if($operation == "remove") {
		
		$result = mysql_query("DELETE FROM materi WHERE id=".$id);
	
		if($result){
			echo 'success';
		}else{
			echo 'failed';
		}
		
	}
?>
